package com.suxin.netty;

import com.suxin.netty.client.MyClientSimpleChannelInboundHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.net.InetSocketAddress;

/**
 * @author Tang
 * @classname NettyClient
 * @description [  ]
 * @date 2021/7/18 10:57
 */
public class NettyClient {

    public static void main(String[] args) throws Exception {

        Bootstrap bootstrap = new Bootstrap();

        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup(8);

        bootstrap.group(nioEventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline()
//                        .addLast("StringDecoder", new StringDecoder())
//                        .addLast("StringEncoder", new StringEncoder())
//                        .addLast("ProtocolByteToMessageDecoder", new ProtocolByteToMessageDecoder())
//                        .addLast("ProtocolMessageToByteEncoder", new ProtocolMessageToByteEncoder())
//                        .addLast("MyClientSimpleChannelInboundHandler", new MyClientSimpleChannelInboundHandler());
                        .addLast("LengthFieldBasedFrameDecoder", new LengthFieldBasedFrameDecoder(
                                1024, 6, 4,4,10))
                        .addLast("MyClientSimpleChannelInboundHandler", new MyClientSimpleChannelInboundHandler());
            }
        });
        ChannelFuture future = bootstrap
                .connect(new InetSocketAddress("127.0.0.1", 9999))
                .addListener(new GenericFutureListener<Future<? super Void>>() {
                    @Override
                    public void operationComplete(Future<? super Void> future) throws Exception {
                        System.out.println("客户端是否连接成功:" + future.isSuccess());
                    }
                })
                .sync();
        future.channel().closeFuture().sync();
    }

}